<template>
  <div class="tab">
    <div class="items" @wheel="onWheel" ref="itemsEl">
      <CompTabItem class="item" v-for="(tab,index) in tabs"
                   @click="onClickTabItem(tab.id)"
                   :data="tab"
                   :key="index">
        {{ tab.name }}
      </CompTabItem>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType, provide, ref, watch } from 'vue';
import { generate } from 'shortid';
import { ProvideKey, TabItem } from './index';
import CompTabItem from './tab-item.vue';

export default defineComponent({
  name: 'tabs',
  components: { CompTabItem },
  emits: ['select', 'close', 'update:data'],
  props: {
    data: {
      type: Array as PropType<TabItem[]>,
      default: () => {
        return [];
      },
    },
  },
  setup(props, { emit }) {
    function completionData(data: TabItem[]) {
      return data.map((prop: TabItem) => {
        return Object.assign({ id: generate(), selected: false, canClose: true }, prop);
      });
    }

    const tabs = ref<TabItem[]>(completionData(props.data));

    watch(() => [...props.data], (val, oldValue) => {
      tabs.value = completionData(val);
    }, { deep: true, immediate: true });
    provide(ProvideKey.CloseTab, (data: TabItem) => {
      const idx = tabs.value.findIndex(el => el.id === data.id);
      if (idx !== -1) {
        const del = tabs.value.splice(idx, 1)[0];
        emit('update:data', tabs.value);
        emit('close', del);
      }
    });
    const itemsEl = ref();
    return {
      tabs,
      itemsEl,
      onClickTabItem(id: string) {
        tabs.value.forEach((tab: TabItem) => {
          const b = (id === tab.id);
          if (b !== tab.selected) {
            tab.selected = b;
            if (b) {
              emit('update:data', tabs.value);
              emit('select', tab);
            }
          }
        });
      },
      onWheel(event: WheelEvent) {
        const left = itemsEl.value.scrollLeft + event.deltaY * 0.7;
        itemsEl.value.scrollTo({ left, behavior: 'smooth' });
      },
    };
  },
});
</script>
<style scoped lang="scss">
.tab {
  display: flex;
  flex-direction: column;
  border-bottom: 1px solid #404040;

  .items {
    display: flex;
    flex-direction: row;
    overflow-x: scroll;

    &::-webkit-scrollbar {
      width: 0;
      height: 0;
    }
  }
}
</style>
